Post not yet marked as solved
I am trying to load and view several locations onto a map from a JSOPN file in my SwiftUI project, but I continually encounter the error "no exact matches in call to initializer" in my ContentView.swift file.
What I Am Trying to Do:
I am working on a SwiftUI project where I need to display several locations on a map. These locations are stored in a JSON file, which I have successfully loaded into Swift. My goal is to display these locations as annotations on a Map view.
JSON File Contents:
coordinates: latitude and longitude
name: name of the location
uuid: unique identifier for each location
Code and Screenshots:
Here are the relevant parts of my code and the error I keep encountering:
import SwiftUI
import MapKit
struct ContentView: View {
@State private var mapPosition = MapCameraPosition.region(
MKCoordinateRegion(
center: CLLocationCoordinate2D(latitude: 37.7749, longitude: -122.4194),
span: MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
)
)
@State private var features: [Feature] = []
var body: some View {
NavigationView {
Map(position: $mapPosition, interactionModes: .all, showsUserLocation: true) {
ForEach(features) { feature in
Marker(coordinate: feature.coordinate) {
FeatureAnnotation(feature: feature)
}
}
}
.onAppear {
POILoader.loadPOIs { result in
switch result {
case .success(let features):
self.features = features
case .failure(let error):
print("Error loading POIs: \(error.localizedDescription)")
}
}
}
.navigationBarTitle("POI Map", displayMode: .inline)
}
}
}
struct FeatureAnnotation: View {
let feature: Feature
var body: some View {
VStack {
Circle()
.strokeBorder(Color.red, lineWidth: 2)
.background(Circle().foregroundColor(.red))
.frame(width: 20, height: 20)
Text(feature.name)
}
}
}
I have not had any luck searching for solutions to my problems using the error messages that keep arising. Does anyone have any advice for how to move forward?
Post not yet marked as solved
this is an email I have sent to Apple with no luck:
Dear Apple Developer Support Team,
I am writing to seek urgent assistance with a persistent issue I
have been encountering with Xcode. For several months now, every
time I connect my iPhone to Xcode for development purposes, it
automatically overwrites the user data of my apps with an old,
seemingly random container. This issue is severely impacting my
ability to continue development, as I cannot test new changes
effectively. This occurs since a few months in every iOS and
Xcode/macOS Version. I tried it with different Apps and Devices.
Sometimes the entire Container (Documents) gets read only access so
no new data can be created or changed by the user.
I frequently used the replace container feature on Xcode so maybe
this has something to do with it.
This problem persists despite numerous attempts to resolve it on my
end. I am at a critical point in my development timeline, and it is
crucial for me to resolve this as soon as possible.
Could you please advise on the next steps I should take to address
this issue? If there are any logs or further information you
require, I am more than willing to provide them.
Thank you for your attention to this matter. I look forward to your
prompt response and hope for a resolution soon.
Best regards,
Victor Lobe
Post not yet marked as solved
Hi, ho un'idea per un'applicazione che può rivoluzionare e agevolare riguardo l'utilizzo degli apparati video (telefoni, monitor, tv) per almeno il75/80% dell'intera popolazione mondiale.
Vorrei che fosse un'operazione realizzata inizialmente da apple ios/os e in seguito su tutti i supporti.
Mi piacerebbe creare, sviluppare o cedere l'idea ma non so proprio da dove iniziare.
potete darmi info su questo?
so che può sembrare una richiesta astrana, ma sono certo che questa app sarà una vera rivoluzione per tutti, o quasi
Grazie
Giovanni da Cagliari, Sardegna, Italia
Hi, I have an idea for an application that can revolutionize and facilitate the use of video equipment (telephones, monitors, TVs) for at least 75/80% of the entire world population.
I would like it to be an operation carried out initially by apple ios/os and later on all media.
I would like to create, develop or sell the idea but I really don't know where to start.
can you give me info on this?
I know it may seem like a strange request, but I'm sure that this app will be a real revolution for everyone, or almost everyone
Thank you
Giovanni from Italy
[Edited by Moderator]
I'm trying to get the same path you'd get by running getconf DARWIN_USER_CACHE_DIR in the terminal, but via
FileManager.default.urls(for: , in:) , but can't really find out how
is there a way to do that other than running the shell script via swift?
Post not yet marked as solved
If I set the capacity of the disk cache to less than 5MB, It doesn't work.
Through the print statement, I checked that the value of the currentDiskUsage did not rise at all, and I also checked that the image has been making network requests every time because there is no cached data even if I shut down and run the app again. I'm simply wondering why this is happening.
Also, I wonder what kind of eviction policy the disk cache follows.
I was so curious that I tried to find out through the link [here], but there seems to be no implementation of disk cache at all.
Below is the code I used. I'm attaching it together just in case.
import UIKit
protocol Cacheable {
func getCachedResponse(
for path: String,
completion: @escaping (Result<Data, CacheError>) -> Void
)
func save(
for path: String,
data: Data
)
}
final class CacheManager {
static let shared = CacheManager()
private let imageCache: URLCache
init() {
imageCache = URLCache(
memoryCapacity: 4 * 1024 * 1024, // 4MB
diskCapacity: 4 * 1024 * 1024 // 4MB
)
}
}
extension CacheManager: Cacheable {
func getCachedResponse(
for path: String,
completion: @escaping (Result<Data, CacheError>) -> Void
) {
if let url = URL(string: path),
let cachedResponse = imageCache.cachedResponse(for: URLRequest(url: url)) {
completion(.success(cachedResponse.data))
return
}
completion(.failure(.noCachedResponse))
}
func save(
for path: String,
data: Data
) {
guard let url = URL(string: path) else { return }
let response = URLResponse(
url: url,
mimeType: nil,
expectedContentLength: 0,
textEncodingName: nil
)
if let uiImage = UIImage(data: data),
let compressedData = uiImage.jpegData(compressionQuality: 0.8) {
#if DEBUG
let formmatter = ByteCountFormatter()
formmatter.allowedUnits = [.useMB]
formmatter.countStyle = .file
print("""
=== Original size: \(formmatter.string(fromByteCount: Int64(data.count)))
=== Cached size: \(formmatter.string(fromByteCount: Int64(compressedData.count)))
""")
#endif
let cachedResponse = CachedURLResponse(
response: response,
data: compressedData
)
imageCache.storeCachedResponse(
cachedResponse,
for: URLRequest(url: url)
)
}
}
}
Post not yet marked as solved
Hi everyone,
I created an IAP
When I filled a the information in the require database, my internet was broken.
When the internet in working normally, I create it again (I didn't save it before I lost my internet)
The system reported an error "The Product ID you entered is already being used by another in-app purchase associated with this app."
Question:
Why can't I reuse a Product ID that I haven't saved before?
Please reply to me soon,
Thank you so much
Post not yet marked as solved
I have an app with which users take photos and upload them in batches. It's used often on older devices, in areas with less than ideal network, and for durations of a full workday - so often the device has low power.
The current implementation of uploads uses an NSURLSession configured for the foreground, and as a result my users are used to having to keep the app in the foreground while an upload completes. However, these uploads are big and connectivity is often low, so this takes a long time - often users are stuck waiting with the app foregrounded for 15 minutes or so while the upload completes.
So, I created a build which uses an NSURLSession configured for the background. In the ideal case, users could start the upload, put the device in their pocket and continue their workday, and the next time they open their device it will be complete.
For some users this ideal case has come true. However, for others, the uploads sit in progress for an indeterminate amount of time, making no progress. My suspicion is that this is because the OS is deferring them until a time when network and power is more available. However, my users are using work devices at a work location - reliable power and network might never be available. Being able to background the app and continue working is valuable for these users, but having the upload complete promptly is essential for them.
My questions are:
Is it true that background configured NSURLSessions will defer network requests when connectivity or power is low, even if discretionary = NO? Is the exact behavior for when requests will be attempted in the background documented?
Is there a way to reliably test background configured NSURLSessions in XCode? I've attempted throttling my connection with Charles Proxy, and using my device in Low Power Mode, but I'm unable to reproduce the request stalling behavior my users are experiencing in the wild.
Is there a way to create an NSURLSession that will muscle through difficult or inefficient uploads in the background, with the same reliability as a foreground session?
If not, what is Apple's recommended approach to situations like mine? I've considered queueing both a background and foreground upload, and cancelling the other once one completes, but this seems disrespectful to the user's resources.
Will setting timeoutIntervalForResource to a lower value cause the OS to more aggressively attempt uploads? Or simply to throw an error sooner? I want the OS to give the upload a long time to complete, but I also want it to attempt it right away.
Thanks for any information!
Post not yet marked as solved
How to use Custom URLSession in MKMapView?
URLSession.shared.downloadTask doesn't work apple watch. I monitored network traffic but it doesn't. have any activity. Data(contentsOf: URL(string: url)!) works perfectly. Also, it works perfectly in preview. What do i do? Ask for more context if necessary.
I tried to read an Object :
-(NSMutableDictionary*) readMyObject:(NSData*)data;
{
NSError * error;
Class class = [NSMutableDictionary class];
NSMutableDictionary * dict;
dict = [NSKeyedUnarchiver unarchivedObjectOfClass:class
fromData:data error:&error];
return dict;
the result was nil.
I searched by Developer for a solution and found one :
{
// NSKeyedUnarchiver * unarchiver = [[NSKeyedUnarchiver alloc] init];
[unarchiver decodeObjectOfClasses:
[[NSSet alloc]initWithArray:
@[[NSDictionary class],
[NSMutableDictionary class],
[NSArray class],
[NSMutableArray class],
[NSString class], [NSNumber class]]]
forKey:NSKeyedArchiveRootObjectKey];
[unarchiver finishDecoding];
}
The first line was from me and it crashed the project.
I assume there is an easy answer, not for me.🥲
Uwe
Post not yet marked as solved
Hello,
I am using CAMetalDisplayLink to render my metal layer and i am trying to calculate timestamp for next render to compare with current timestamp.
I did notice that timestamp from display link Update is not like Date timestamp. Looks like it depends on some kind of phone boot or another kernel process start. I did try
func bootTime() -> TimeInterval? {
var tv = timeval()
var tvSize = MemoryLayout<timeval>.size
let err = sysctlbyname("kern.boottime", &tv, &tvSize, nil, 0);
guard err == 0, tvSize == MemoryLayout<timeval>.size else {
return nil
}
return Double(tv.tv_sec) + Double(tv.tv_usec) / 1_000_000.0
}
And i got
calc
1715680889.6883893
real
1715680878.01257
It's close but still 10 seconds different so probably it's not kern.boottime but something similar.
Anybody knows what should i use to get correct timestamp?
I had some support tickets about dates not showing properly for customers based in the America/Merida timezone.
Essentially America/Merida permanently changed to -0500 (CDT) on October 31, 2021, and it appears that the NSTimeZone does not respect this change, and reports times as -0600 (CST).
Creating a little test tool with the following code:
+(void) run {
NSArray<NSString *> * args = [[NSProcessInfo processInfo] arguments];
if ([args count] > 1) {
NSString *timezone = args[1];
NSLog(@"custom TZ: %@", timezone);
NSTimeZone * tz = [NSTimeZone timeZoneWithName:timezone];
[NSTimeZone setDefaultTimeZone:tz];
}
NSDate * now = [NSDate date];
NSLog(@"Testing Dates: (local timezone : %@)", [NSTimeZone localTimeZone]);
NSLog(@" (default timezone: %@)", [NSTimeZone defaultTimeZone]);
NSLog(@" (is DST : %@)", [[NSTimeZone defaultTimeZone] isDaylightSavingTimeForDate:now] ? @"YES" : @"NO");
NSLog(@" (current cal-tz : %@)", [[NSCalendar currentCalendar] timeZone]);
NSLog(@" (current locale : %@)", [[NSLocale currentLocale] localeIdentifier]);
NSLog(@"Now: %@", now);
}
And running with the America/Merida timezone passed in, I'm getting the following output:
custom TZ: America/Merida
Testing Dates: (local timezone : Local Time Zone (America/New_York (EDT) offset -14400 (Daylight)))
(default timezone: America/Merida (CST) offset -21600)
(is DST : NO)
(current cal-tz : America/Merida (CST) offset -21600)
(current locale : en_US)
Now: Tue May 14 15:06:14 2024
Running the same code on Linux via the GNUStep implementation of Objective-C, I get the correct output with America/Merida showing up as CDT (ie (is DST : YES)).
Are there any good ways to work around this?
Post not yet marked as solved
Hi! Not sure if this is a swift data or more a Decimal in general type of question.
What's going on:
I have a SwiftUI app using SwiftData, I have persisted a Model with a property "reducedPrice" of type Decimal. It's stores correctly the value.
Now, I have read the value during automated tests and tried comparing the values:
let reducedPrice = model.reducedPrice // swift data property
let target = Decimal(4.98) // expected target value to compare to swift data value.
Now if I just print the result of the comparison between those 2 I get a false result.
print(reducedPrice == target) //output : false
The swift data model was populated from a direct copy of another struct that comes from an JSON import using Codable+CodingKeys (I used Decimal type).
What I expected:
I expected it to be true.
Debug Observations
I did noticed that on the variable inspector both had the same magnitudes but in reality the mantissa are different. I'm attaching a screenshot.
My Theory
They are different just because something under SwiftData stores different way the decimal as in comparison on how I am creating the Decimal for the comparison inside the automated tests.
My question
Is this expected behavior?
Any suggestion on best practices on how to handle this?
Thank you in advance any relevant guidance is very appreciated!
Post not yet marked as solved
Hey there,
I'm trying to decode an json with an dynamic dict as value.
eg.
"results": [
{
"id": 1799,
"created_at": "2024-05-09T14:21:13.289655Z",
"updated_at": "2024-05-10T11:54:25.484537Z",
"email": "test@test.testh",
"name": "Test",
"attributes": {
"name": {
"firstname": "max",
"lastname": "mustermann"
},
"anboolen": false,
"anNumber": 1,
"anString": "Test"
}
}
]
The dictionary "attributes" is always an dictionary but the content inside could be everything.
for the container of results I already created an struct and using JSONDecoder to decode, but now I have the issue with the attributes part.
Can anyone help me with this issue?
Thanks in advance!
Post not yet marked as solved
This error only occurs in device with 17.4.1 OS. Can anyone please help me in this ?
Post not yet marked as solved
I have an Electron app on macOS Sonoma (Intel arch). It has a native addon (app.node) using node-addon-api. Recently it crashed, with the stack trace (given below). What is the CF_IS_OBJC function inside the CFDataGetBytePtr function, and why did it crash there?
[NSEvent addGlobalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^(NSEvent *event) {
// code using CFDataGetBytePtr function
}];
[NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskKeyDown handler:^NSEvent *_Nullable(NSEvent *event) {
// code using CFDataGetBytePtr function
return event;
}];
I have key events monitors attached using addGlobalMonitorForEventsMatchingMask and addLocalMonitorForEventsMatchingMask in my native code and they use the CFDataGetBytePtr function there. So I think the issue happened in the key event monitor handler when calling the CFDataGetBytePtr function because my native addon app.node is also present in the trace. Also from the third and fourth entry in the stack trace, it seems like it happened while the app was updating.
OS Version: macOS 14.4 (23E214)
Report Version: 104
Crashed Thread: 5490
Application Specific Information:
Fatal Error: EXC_BAD_ACCESS / KERN_INVALID_ADDRESS / 0x0
Thread 5490 Crashed:
0 CoreFoundation 0x19c970118 CF_IS_OBJC
1 CoreFoundation 0x19c83b280 CFDataGetBytePtr
2 .app.desktop.1inmRz 0x104a5bec0 <unknown>
3 .app.desktop.1inmRz 0x104a57b28 <unknown>
4 app.node 0x104a80a7c [inlined] Napi::details::CallbackData<T>::Wrapper::lambda::operator() (napi-inl.h:117)
5 app.node 0x104a80a7c Napi::details::WrapCallback<T> (napi-inl.h:79)
6 app.node 0x104a80a24 Napi::details::CallbackData<T>::Wrapper (napi-inl.h:112)
7 Electron Framework 0x11472e5e0 v8impl::(anonymous namespace)::FunctionCallbackWrapper::Invoke (js_native_api_v8.cc:441)
8 <unknown> 0x147e105f8 <unknown>
9 <unknown> 0x1401d0814 <unknown>
10 <unknown> 0x1401d0a9c <unknown>
11 <unknown> 0x147f19368 <unknown>
12 <unknown> 0x147e0aab0 <unknown>
13 <unknown> 0x1401d0e00 <unknown>
14 <unknown> 0x1401d1ac0 <unknown>
15 <unknown> 0x147f19368 <unknown>
16 <unknown> 0x147e0aab0 <unknown>
17 <unknown> 0x1401d1494 <unknown>
18 <unknown> 0x1401d20dc <unknown>
19 <unknown> 0x147e4c1b4 <unknown>
20 <unknown> 0x147f1b5f8 <unknown>
21 <unknown> 0x147e3b754 <unknown>
22 <unknown> 0x147e0b618 <unknown>
23 Electron Framework 0x10ee0c49c v8::internal::(anonymous namespace)::Invoke (simulator.h:178)
24 Electron Framework 0x10ee0d08c v8::internal::(anonymous namespace)::InvokeWithTryCatch (execution.cc:475)
25 Electron Framework 0x10ee0d1e0 v8::internal::Execution::TryRunMicrotasks (execution.cc:576)
26 Electron Framework 0x10ee37364 v8::internal::MicrotaskQueue::PerformCheckpoint (microtask-queue.cc:176)
27 Electron Framework 0x1146cce9c node::InternalCallbackScope::Close (callback.cc:137)
28 Electron Framework 0x1146ccb64 node::InternalCallbackScope::~InternalCallbackScope (callback.cc:92)
29 Electron Framework 0x1147112b4 node::Environment::RunTimers (env.cc:1376)
30 Electron Framework 0x10daf9980 uv__run_timers (timer.c:178)
31 Electron Framework 0x10dafcb3c uv_run (core.c:465)
32 Electron Framework 0x10dc944d4 electron::NodeBindings::UvRunOnce (node_bindings.cc:891)
33 Electron Framework 0x110e2016c base::TaskAnnotator::RunTaskImpl (callback.h:156)
34 Electron Framework 0x110e3cea4 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::DoWork (task_annotator.h:89)
35 Electron Framework 0x110e8851c base::MessagePumpCFRunLoopBase::RunWorkSource (message_pump_apple.mm:444)
36 Electron Framework 0x10da7ad7c base::apple::CallWithEHFrame
37 Electron Framework 0x110e876a4 base::MessagePumpCFRunLoopBase::RunWorkSource (message_pump_apple.mm:415)
38 CoreFoundation 0x19c89deac __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__
39 CoreFoundation 0x19c89de40 __CFRunLoopDoSource0
40 CoreFoundation 0x19c89dbb0 __CFRunLoopDoSources0
41 CoreFoundation 0x19c89c79c __CFRunLoopRun
42 CoreFoundation 0x19c89be08 CFRunLoopRunSpecific
43 HIToolbox 0x1a7036ffc RunCurrentEventLoopInMode
44 HIToolbox 0x1a7036e38 ReceiveNextEventCommon
45 HIToolbox 0x1a7036b90 _BlockUntilNextEventMatchingListInModeWithFilter
46 AppKit 0x1a00f496c _DPSNextEvent
47 AppKit 0x1a08e6de8 -[NSApplication(NSEventRouting) _nextEventMatchingEventMask:untilDate:inMode:dequeue:]
48 AppKit 0x1a00e7cb4 -[NSApplication run]
49 Electron Framework 0x110e89244 base::MessagePumpNSApplication::DoRun (message_pump_apple.mm:805)
50 Electron Framework 0x110e87068 base::MessagePumpCFRunLoopBase::Run (message_pump_apple.mm:156)
51 Electron Framework 0x110e3d9a0 base::sequence_manager::internal::ThreadControllerWithMessagePumpImpl::Run (thread_controller_with_message_pump_impl.cc:646)
52 Electron Framework 0x110e05a98 base::RunLoop::Run (run_loop.cc:134)
53 Electron Framework 0x10ffcbcd0 content::BrowserMainLoop::RunMainMessageLoop (browser_main_loop.cc:1094)
54 Electron Framework 0x10ffcd744 content::BrowserMainRunnerImpl::Run (browser_main_runner_impl.cc:158)
55 Electron Framework 0x10ffc964c content::BrowserMain (browser_main.cc:34)
56 Electron Framework 0x10de12aa8 content::RunBrowserProcessMain (content_main_runner_impl.cc:712)
57 Electron Framework 0x10de13b1c content::ContentMainRunnerImpl::RunBrowser (content_main_runner_impl.cc:1299)
...
Post not yet marked as solved
My Objective-C app contains several hundreds lines of deprecated code like these:
NSData *tmp = [NSKeyedArchiver archivedDataWithRootObject:singleTaskCleanUserArrayItem];
singleTaskUserArrayItem = [NSKeyedUnarchiver unarchiveObjectWithData:tmp];
New recommended methods:
+archivedDataWithRootObject:requiringSecureCoding:error:
+unarchivedObjectOfClass:fromData:error:
How to implement the new methods in Objective-C?
Forums and Documentation refer to Swift but not to Objective-C. Please give me a sample code for the two lines of code
Best regards,
Gerhard
Post marked as Apple Recommended
Hi,
I am facing a strange issue in my app with iOS14 there is a intermittent crash, i am using NetServiceBrowser for MDNS discovery not sure if that is causing the problem crash log has below information:
Crashed: com.apple.main-thread
0 CoreFoundation 0x1a906c4c4 CFAssertMismatchedTypeID + 108
1 CoreFoundation 0x1a8f7db0c CFRunLoopSourceRemoveFromRunLoop + 298
2 CFNetwork 0x1a96255b0 CFNetServiceBrowserStopSearch + 460
3 CoreFoundation 0x1a8f81240 CFRUNLOOPISCALLINGOUTTOASOURCE0PERFORMFUNCTION + 24
4 CoreFoundation 0x1a8f81140 CFRunLoopDoSource0 + 204
5 CoreFoundation 0x1a8f80488 CFRunLoopDoSources0 + 256
6 CoreFoundation 0x1a8f7aa40 CFRunLoopRun + 776
7 CoreFoundation 0x1a8f7a200 CFRunLoopRunSpecific + 572
8 GraphicsServices 0x1bf075598 GSEventRunModal + 160
9 UIKitCore 0x1ab840004 -[UIApplication run] + 1052
10 UIKitCore 0x1ab8455d8 UIApplicationMain + 164
Post not yet marked as solved
Im making an API call using notions API to access and retrieve data from my Notion page and I'm successfully making the url request and accessing the page, however I seem to be struggling with returning the actual data that I have in that page and parsing the JSON data as right now, my console only outputs the makeup of my notion page rather than the formatted and parsed data. I made a codable struct meant to replicate the structure of a notion page based off their documentation then I'm passing that struct to my JSON parsing function but my data still is not being parsed and returned. heres what I have.
import Foundation
struct Page: Codable, Hashable { //Codable struct for notion "Page" for defining content aswell as object representation in a codable struct of all the basic components that make up a notion page per notion's documentation
let created_time: String
let created_by: String
let last_edited_time: String
let object: String
let cover: String
let emoji: String
let icon: String
struct properties: Codable, Hashable {
let title: String
let dueDate: String
let status: String
}
struct dueDate: Codable, Hashable {
let id: String
let type: String
let date: String
let start: String
let end: String? //optionals added to "end" and "time_zone" as these values are set to null in the documentation
let time_zone: String?
}
struct Title: Codable,Hashable {
let id: String
let type: String
let title: [String]
}
struct annotations: Codable, Hashable {
let bold: Bool
let italic: Bool
let strikethrough: Bool
let underline: Bool
let code: Bool
let color: String
}
let English: String
let Korean: String
let Pronounciation: String
let in_trash: Bool
let public_url: String?
let annotations: Bool
}
let url = URL(string: "https://api.notion.com/v1/pages/8efc0ca3d9cc44fbb1f34383b794b817")
let apiKey = "secret_Olc3LXnpDW6gI8o0Eu11lQr2krU4b870ryjFPJGCZs4"
let session = URLSession.shared
func makeRequest() {
if let url = url {
var request = URLRequest(url: url)
let header = "Bearer " + apiKey //authorization header declaration
request.addValue(header, forHTTPHeaderField: "authorization") //append apikey
request.addValue("2022-06-28",forHTTPHeaderField: "Notion-Version") //specify version per notions requirments
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let httpError = error {
print("could not establish HTTP connection:\(httpError)")
} else {
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
} else {
print("invalid api key:\(httpResponse.statusCode)")
}
}
}
if let unwrapData = data { //safely unwrapping the data value using if let
if let makeString = String(data: unwrapData, encoding: .utf8) {
print(makeString)
} else {
print("no data is being returned:")
}
do {
let decoder = JSONDecoder() //JSONDecoder method to decode api data,
let codeUnwrappedData = try decoder.decode(Page.self,from: unwrapData) //Page. specifies its a struct, from: passes the data parmeter that contains the api data to be decoded //PASS STRUCTURESDATABASE STRUCT
print("data:\(codeUnwrappedData)")
} catch {
print("could not parse json data")
}
if let httpResponse = response as? HTTPURLResponse {
if httpResponse.statusCode == 200 {
print(String(data: unwrapData, encoding: .utf8)!)
} else {
print("unsuccessful http response:\(httpResponse)")
}
}
}
}
task.resume()
}
}
Post not yet marked as solved
HI i have coded an App for Mac OSX that has embedded a Command line tool, the problem is that everything works fine while i am running from the xcode compiler, after build the final product, the app is not working properly and i can see messages like this in the console.
Task .<251932> not allowed to create a new connection (existing Connection 224)
Task <37752B7F-5827-4160-83C4-773B17AE72DF>.<255990> resuming, timeouts(60.0, 604800.0) QOS(0x21) Voucher (null)
i was reading a link posted here but the solution is not working, some ideas are appreciated.
My guess is that maybe is something related with a security setting.
This is the code:
NSTask *task;
NSString *executableName = @"websocat";
NSString *executablePath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:executableName];
task = [[NSTask alloc] init];
[task setLaunchPath:executablePath];
Quinn “The Eskimo!" please help!